<template>
  <div class="wrapper">
    <el-header height="70px">
      <home-header @goLink="goLink" />
    </el-header>
    <div @click="closeModal" class="center">
      <div class="center-link">
        <span @click="changeMap(3)">单机年收入</span>
        <span @click="changeMap(4)">单机年利润</span>
        <span @click="changeMap(0)">患者数</span>
        <span @click="changeMap(2)">上机率</span>
        <span @click="changeMap(1)">新增数</span>
      </div>
      <div :style="{ height: `${mapHeight}px` }" id="mapChart"></div>
      <div class="left">
        <!-- 设备登录数 -->
        <div class="left-top">
          <left-top
            :deviceNum="deviceNum"
            :lastDialysis="lastDialysis"
            :rotopathyOptionsrData="rotopathyOptionsrData"
            @shwDeviceNum="shwDeviceNum"
          />
        </div>
        <div class="left-center">
          <left-center
            :dialysisChartData="dialysisChartData"
            :ktvChartData="ktvChartData"
            :urrChartData="urrChartData"
          />
        </div>
        <div class="left-bottom">
          <left-bottom :pieChartData="pieChartData" :txTypeData="txTypeData" />
        </div>
      </div>
      <div class="right">
        <div class="right-top">
          <right-top
            :machineChartData="machineChartData"
            @shwDeviceNum="shwDeviceNum"
          />
        </div>
        <div class="right-center">
          <right-center
            :incomeChartData="incomeChartData"
            @shwDeviceNum="shwDeviceNum"
          />
        </div>
        <div class="right-bottom">
          <right-bottom
            :consumableChartData="consumableChartData"
            :drugChartData="drugChartData"
            @onCategoryChange="onCategoryChange"
            @shwDeviceNum="shwDeviceNum"
          />
        </div>
      </div>
      <div
        :style="{ left: `${pLeft}%` }"
        @click="shwDeviceNum(5)"
        class="bottom-charts"
      >
        <el-card shadow="never">
          <div @click="showImg" class="title-wrapper">
            <div class="chart-title">昨日新增数</div>
          </div>
          <div class="chart-content">
            <span :key="index" v-for="(item, index) in lastAdd">{{
              item
            }}</span>
          </div>
        </el-card>
        <el-card shadow="never">
          <div @click="showImg" class="title-wrapper">
            <div class="chart-title">昨日退出数</div>
          </div>
          <div class="chart-content">
            <span :key="index" v-for="(item, index) in lastExit">{{
              item
            }}</span>
          </div>
        </el-card>
      </div>
      <!-- :style="dynicPosition" -->
      <div class="patient-wrapper">
        <div class="patient-chart-wrapper">
          <div
            class="chart-title"
            style="margin-left: 80px; box-sizing: border-box"
          >
            中心患者数
          </div>
          <v-chart :options="patientTotalChart" style="height:400px" />
        </div>
      </div>
    </div>
    <div :style="modelStyle" class="modal-style" v-if="modelShow">
      <div class="header">
        <span class="title">{{ provinceName }}</span>
        <div @click="closeModal" class="close">
          <span>关闭</span>
          <i class="el-icon-close el-icon--right"></i>
        </div>
      </div>
      <div class="body">{{ info }}</div>
    </div>
    <el-dialog
      :before-close="handleClose"
      :visible.sync="dialogVisible"
      width="60%"
    >
      <el-Image :src="imgSrc" fit="fit"></el-Image>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request'
import HomeHeader from './components/Home/header.vue'
import chinaMapData from '../../public/china.json'
// 左侧上部 设备数，在透数
import LeftTop from './components/HomeLeft/LeftTop.vue'
import LeftCenter from './components/HomeLeft/LeftCenter.vue'
import LeftBottom from './components/HomeLeft/LeftBottom.vue'
import RightTop from './components/HomeRight/RightTop.vue'
import RightCenter from './components/HomeRight/RightCenter.vue'
import RightBottom from './components/HomeRight/RightBottom.vue'

const screenWidth = document.documentElement.clientWidth
const screenHeight = document.documentElement.clientHeight
// import DeviceCount from './components/DevivceCount'
export default {
  components: {
    HomeHeader,
    LeftTop,
    LeftCenter,
    LeftBottom,
    RightTop,
    RightCenter,
    RightBottom
  },
  props: {},
  data() {
    return {
      modelShow: false,
      dialogVisible: false,
      modelLeft: '',
      modelright: '',
      ecbox: {
        width: 800,
        height: 600
      },
      ecmodel: {
        width: 300,
        height: 280
      },
      modelStyle: {
        left: '',
        top: ''
      },
      // 登录设备数
      deviceNum: [0, 0, 0],
      // 昨日在透数
      lastDialysis: [2, 6, 9],
      // 原发病数据
      rotopathyOptionsrData: [],
      // 指标合格率 ktv
      ktvChartData: 0.0,
      urrChartData: 0.0,
      pieChartData: [],
      txTypeData: [],
      machineChartData: [],
      dialysisChartData: [],
      incomeChartData: {},
      drugChartData: [],
      consumableChartData: [],
      radioSelected: '药品',
      // 昨日新增数
      lastAdd: [],
      // 昨日退出数
      lastExit: [],
      // 中心患者数
      patientTotalChart: {},
      provinceName: '',
      info: '',
      imgSrc: ''
    }
  },
  computed: {
    mapHeight() {
      // if (screenWidth < 1600) return 700
      // return 850
      return screenHeight - 71
    },
    pLeft() {
      if (screenWidth < 1600) {
        return 40
      }
      return 35
    },
    dynicPosition() {
      if (screenWidth > 1600) {
        return 'right: 380px;top: 350px;width: 280px;'
      }
      return 'right: 330px;top: 430px;width: 260px;'
    }
  },
  methods: {
    // 登录设备数
    initDeviceNum() {
      axios
        .get('/api/hq/dashboard/device/sum/total')
        .then(res => {
          // console.log('设备数据1', res)
          this.deviceNum = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 昨日在透数
    initOnBoardNum() {
      axios
        .get('/api/hq/dashboard/pre/hd/total')
        .then(res => {
          this.lastDialysis = ['1', '4', '6'] // res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 原发病
    initProtopathy() {
      axios
        .get('api/hq/dashboard/hd/primary/disease/distribution')
        .then(res => {
          this.rotopathyOptionsrData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 指标合格率
    initKtvChart() {
      axios
        .get('/api/hq/dashboard/all/sp/kt/v/qualify/rate')
        .then(res => {
          this.ktvChartData = res
        })
        .catch(err => {
          console.log(err)
        })
      axios
        .get('/api/hq/dashboard/all/sp/kt/v/qualify/rate')
        .then(res => {
          this.urrChartData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    initUrrChart() {
      axios
        .get('/api/hq/dashboard/all/sp/kt/v/qualify/rate')
        .then(res => {
          this.urrChartData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 透析频次
    initDialysisFrequency() {
      axios
        .get('/api/hq/dashboard/hd/frequency/distribution')
        .then(res => {
          this.dialysisChartData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 地图初始化
    initMap(type, res) {
      const xData = []
      const yData = []
      const imgs = [
        'image://' + require('@/assets/images/position_p.png'),
        'image://' + require('@/assets/images/position_r.png'),
        'image://' + require('@/assets/images/position_g.png'),
        'image://' + require('@/assets/images/position_y.png'),
        'image://' + require('@/assets/images/position_pu.png')
      ]
      const unitname = ['人', '人', '%', '万元', '%']
      this.$echarts.registerMap('china', chinaMapData)
      const chartDom = document.getElementById('mapChart')
      const chart = this.$echarts.init(chartDom)
      const _this = this
      chart.on('click', param => {
        param.event.event.stopPropagation()
        _this.modelShow = true
        _this.getInfoByProvince(param.name)
        _this.provinceName = param.name
        const mw = window.event
        if (_this.ecbox.width - mw.offsetX - 20 > _this.ecmodel.width) {
          _this.modelStyle.left = mw.offsetX + 20 + 'px'
        } else {
          _this.modelStyle.left = mw.offsetX - _this.ecmodel.width - 20 + 'px'
        }
        if (_this.ecbox.height - mw.offsetY - 10 > _this.ecmodel.height) {
          _this.modelStyle.top = mw.offsetY + 'px'
        } else {
          if (_this.info === '暂无该省份医保信息') {
            _this.modelStyle.top =
              mw.offsetY - _this.ecmodel.height + 220 + 'px'
          } else {
            _this.modelStyle.top = mw.offsetY - _this.ecmodel.height + 60 + 'px'
          }
        }
      })
      const _regions = []
      res = res.sort((a, b) => {
        return b.total - a.total
      })
      res.map(item => {
        xData.push(item.hospitalName)
        yData.push(item.total)
        _regions.push({
          name: item.provinceRegionName.slice(0, 2),
          label: {
            show: true
          },
          itemStyle: {
            normal: {
              backgroundColor: '#fff',
              areaColor: '#A0CEFC'
            }
          }
        })
        _regions.push({
          name: '南海诸岛',
          value: 0,
          itemStyle: {
            normal: {
              opacity: 0,
              label: {
                show: false
              }
            }
          }
        })
      })
      chart.setOption({
        backgroundColor: 'transparent',
        // title: this.setTitle,
        // grid: this.setGrid,
        tooltip: {
          show: true,
          formatter: params => {
            return params.name + ':' + params.value[2] + unitname[type]
          }
          // trigger: 'item',
          // backgroundColor: '#ff0000',
          // showDelay: 0,
          // hideDelay: 0,
          // enterable: false,
          // transitionDuration: 0
        },
        label: { show: false },
        xAxis: {
          show: false
        },
        yAxis: {
          type: 'category',
          // nameGap: 16,
          inverse: true,
          axisLine: {
            show: false,
            lineStyle: {
              color: '#455B77'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            interval: 0,
            textStyle: {
              color: '#333'
            }
          },
          data: []
        },
        geo: {
          map: 'china',
          roam: false,
          aspectScale: 0.8,
          layoutCenter: ['47%', '47%'],
          layoutSize: screenWidth < 1900 ? '110%' : '130%',
          label: {
            normal: {
              show: false,
              color: '#000' // 省份标签字体颜色
            },
            emphasis: {
              show: true,
              color: '#333' // 鼠标滑过地图后当前区域显示的省份颜色 '#f75a00'
            }
          },
          itemStyle: {
            // 图形上的地图区域
            normal: {
              areaColor: '#CDE5FD', // CDE5FD
              borderColor: 'rgba(0,0,0,0.2)'
            },
            emphasis: {
              // borderColor: '#aed6f2',// '#0066ba',
              areaColor: '#aed6f2',
              color: '#333'
              // shadowColor: 'rgba(0,0,0,0.4)',
              // shadowBlur: 10
            }
          },
          regions: _regions
        },
        visualMap: {
          show: false,
          left: '3%',
          bottom: '5%',
          calculable: true,
          seriesIndex: [0],
          showLabel: true,
          // 数据颜色范围，值越大颜色越深
          inRange: {
            color: ['#CDE5FD', '#8AC3FB', '#63AEFC']
          },
          textStyle: {
            color: '#CDE5FD'
          }
        },
        series: [
          {
            name: '患者分布',
            type: 'map',
            backgroundColor: '#F7FAFC',
            borderColor: '#3096C7',
            borderWidth: 1.5,
            geoIndex: 0,
            zoom: 1.2,
            tooltip: {
              trigger: 'item',
              formatter: p => {
                let val = p.value
                if (p.name === '南海诸岛') {
                  return
                }
                if (window.isNaN(val)) {
                  val = 0
                }
                // const txtCon = `<div style="text-align:left;color:#676A6C;font-size:16px;">
                //                     <h4 style="font-weight: 600;"> ${p.name}: 昨日总收入 <span style="color:#F4516C"> ${val.toFixed(2)} <span> 元</h4>
                //                     <ul style="text-align:left;color:#676A6C;font-size:14px;">
                //                       <li>
                //                         攀钢密地医院：23100元
                //                       </li>
                //                       <li>
                //                         攀钢长寿医院：22100元
                //                       </li>
                //                     </ul>
                //                   </div>`
                // return txtCon
              },
              backgroundColor: '#F7FAFC',
              borderColor: '#3096C7',
              borderWidth: 1.5
            },
            data: res.map(item => {
              // console.log(111, item)
              return {
                name: item.hospitalName,
                value: [parseFloat(item.longitude), parseFloat(item.latitude)],
                itemStyle: {
                  normal: {
                    areaColor: '#f00',
                    color: '#ff7474',
                    shadowBlur: 0,
                    shadowOffsetX: 0
                  }
                }
              }
            }),
            zlevel: 1
          },
          {
            name: 'china',
            type: 'scatter',
            coordinateSystem: 'geo',
            symbol: v => {
              return imgs[type]
            },
            symbolSize: 75,
            label: {
              position: 'center',
              normal: {
                show: true,
                // position: 'center',
                formatter: v => {
                  return v.name + '\n' + v.value[2]
                },
                lineHeight: 16,
                // backgroundColor: 'rgba(255,255,255,.9)',
                // borderRadius: '#80cffd',
                // borderWidth: '1',
                padding: [2, 3, 1, 2],
                color: '#333',
                fontSize: 12,
                fontWeight: 'bold',
                fontFamily: '微软雅黑'
              }
            },
            data: res.map(item => {
              // console.log(111, item)
              return {
                name: item.hospitalName,
                value: [
                  parseFloat(item.longitude),
                  parseFloat(item.latitude),
                  item.total
                ],
                itemStyle: {
                  normal: {
                    areaColor: '#f00'
                  }
                }
              }
            })
          }
        ]
      })
    },
    getInfoByProvince(name) {
      axios
        .get(`/api/hq/dashboard/region/province/policy?provinceName=${name}`)
        .then(res => {
          if (res && res.policyRemark) this.info = res.policyRemark
          else this.info = '暂无该省份医保信息'
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 血管通路分布
    initPieChart() {
      axios
        .get('/api/hq/dashboard/vascular/Access/total/ratio')
        .then(res => {
          this.pieChartData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 透析方式分布
    initTXChart() {
      axios
        .get('api/hq/dashboard/hd/dialysis/mode/distribution')
        .then(res => {
          this.txTypeData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 昨日上机率
    initMachineChart() {
      axios
        .get(
          '/api/hq/dashboard/region/pre/hd/device/use/ratio?today=2021-02-23'
        )
        .then(res => {
          this.machineChartData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 一周总收入
    initTotalIncome() {
      axios
        .get(
          '/api/hq/dashboard/weekday/device/total/income?startdate=2021-02-23'
        )
        .then(res => {
          this.incomeChartData = res
        })
        .catch(err => {
          console.log(222, err)
        })
    },
    // 药品
    initDrugChart() {
      // 药品
      axios
        .get('/api/hq/dashboard/pre/medicine/total/dose?startDate=2021-02-23')
        .then(res => {
          this.drugChartData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 耗材
    initConsumableChart() {
      // 药品
      axios
        .get('/api/hq/dashboard/pre/material/total/qty?startDate=2021-02-23')
        .then(res => {
          this.consumableChartData = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 昨日新增、退出数
    initAddQuitCount() {
      axios
        .get('/api/hq/dashboard/pre/new/patient/total')
        .then(res => {
          this.lastAdd = res
        })
        .catch(err => {
          console.log(err)
        })
      axios
        .get('/api/hq/dashboard/pre/outcome/patient/total')
        .then(res => {
          this.lastExit = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 中心患者数
    initPatientTotalChart() {
      axios
        .get('/api/hq/dashboard/org/patient/summary')
        .then(res => {
          const yData1 = []
          const yData2 = []
          const xData = []
          res.map(item => {
            xData.push(item.hospitalName)
            yData1.push(item.patientTotal)
            yData2.push(item.overflowTotal)
          })
          this.patientTotalChart = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
              }
            },
            legend: {
              data: ['按设备数2班满员数', '溢/缺数']
            },
            grid: {
              left: '7%',
              right: '1%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [
              {
                type: 'value',
                inverse: true,
                axisTick: { show: false },
                axisLabel: { show: false },
                axisLine: { show: false },
                splitLine: {
                  show: false
                }
              }
            ],
            yAxis: [
              {
                type: 'category',
                axisTick: {
                  show: false
                },
                data: xData // ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
              }
            ],
            series: [
              {
                name: '按设备数2班满员数',
                type: 'bar',
                stack: '总量',
                label: {
                  show: true,
                  position: 'left'
                },

                // barMinHeight: 24,
                // barMinWidth: 22,
                itemStyle: {
                  normal: {
                    color: '#45b5ff'
                  }
                },
                data: yData1
              },
              {
                name: '溢/缺数',
                type: 'bar',
                stack: '总量',
                label: {
                  show: true
                  // formatter: p => {
                  //   console.log('p===', p)
                  //   return p.value === 0 ? '' : p.value
                  // }
                  // position: 'center'
                },
                itemStyle: {
                  normal: {
                    color: '#fdd100'
                  }
                },
                barMinHeight: 25,
                data: yData2
              }
            ]
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    goLink(type) {
      if (type === 1) {
        // 质控
        window.open('http://192.168.1.12:8907/')
      } else {
        // 运营
        window.open('http://192.168.1.12:8901/')
      }
    },
    // 昨日药品、耗材切换事件
    onCategoryChange(type) {
      this.radioSelected = type
      if (type === '耗材') {
        this.initConsumableChart()
      } else this.initDrugChart()
    },
    changeMap(type) {
      axios
        .get(`/api/hq/dashboard/region/patient/total?totalType=${type}`)
        .then(res => {
          this.initMap(type, res)
        })
        .catch(err => {
          console.log(err)
        })
    },
    showImg() {
      this.$$emit('showImg')
    },
    openDrugModal() {
      // console.log(111111111111)
    },
    // 点击地图省份弹出层关闭
    closeModal() {
      this.modelShow = false
    },
    // 登录设备数，昨日在透数点击查看二级图
    shwDeviceNum(type) {
      if (type === 1 || type === 5) {
        this.imgSrc = require('@/assets/images/设备分布.png')
      } else if (type === 2) {
        this.imgSrc = require('@/assets/images/一周上机.png')
      } else if (type === 3) {
        this.imgSrc = require('@/assets/images/收入.png')
      } else if (type === 4) {
        this.imgSrc = require('@/assets/images/药品.png')
      }
      this.dialogVisible = true
    },
    handleClose(donw) {
      this.dialogVisible = !this.dialogVisible
    }
  },
  mounted() {
    console.log(2222, document.documentElement.clientHeight)
    this.changeMap(0)
    this.initDeviceNum()
    this.initOnBoardNum()
    // 原发病
    this.initProtopathy()
    // KTV指标
    this.initKtvChart()
    // URR指标
    this.initUrrChart()
    // 透析频次
    this.initDialysisFrequency()
    // 血管通路分布
    this.initPieChart()
    // 透析方式
    this.initTXChart()
    // 昨日上机率
    this.initMachineChart()
    // 一周总收入
    this.initTotalIncome()
    this.initDrugChart()
    this.initAddQuitCount()
    this.initPatientTotalChart()
  }
}
</script>
<style lang="scss" scoped>
.wrapper {
  // 中间整体，左右为浮动
  background: transparent;
  .center {
    position: relative;
    padding: 0;
    width: 100%;
    // height: 850px;
    box-sizing: border-box;
    background: transparent;
    overflow: hidden;
    z-index: 1;
    // &::after {
    //   content: ' ';
    //   display: block;
    //   width: 0;
    //   height: 0;
    //   clear: both;
    //   overflow: hidden;
    // }
    .center-link {
      position: absolute;
      left: 50%;
      margin-left: -220px;
      top: 30px;
      width: 440px;
      display: flex;
      z-index: 102;
      span {
        font-size: 18px;
        font-weight: 600;
        cursor: pointer;
        &:nth-child(1) {
          flex: 1;
          color: rgb(245, 208, 57);
        }
        &:nth-child(2) {
          flex: 1;
          text-align: right;
          color: rgb(118, 110, 115);
        }
        &:nth-child(3) {
          color: rgb(188, 138, 170);
        }
        &:nth-child(4) {
          color: rgb(24, 136, 89);
        }
        &:nth-child(5) {
          color: rgb(201, 31, 68);
        }
        width: 72px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
      }
    }
    .left {
      // float: left;
      position: absolute;
      top: 0;
      left: 0;
      width: 516px;
      height: 100%;
      background: transparent;
      box-sizing: border-box;
      z-index: 2;
      .left-top {
        margin: 10px 0 0 50px;
        height: 230px;
        box-sizing: border-box;
        display: flex;
      }
      .left-center {
        margin-top: 20px;
        margin-left: 50px;
        height: 210px;
        display: flex;
        box-sizing: border-box;
        background: transparent;
      }
      .left-bottom {
        // margin-top: 30px;
        margin-left: 50px;
        height: calc(100% - 440px);
        display: flex;
        box-sizing: border-box;
      }
    }
    .right {
      position: absolute;
      top: 0;
      right: 0;
      margin-right: 10px;
      float: right;
      width: 24%;
      height: 850px;
      box-sizing: border-box;
      .right-top {
        width: 100%;
        height: 230px;
        // border: 1px solid #fff;
      }
      .right-center {
        margin: 10px 0;
        width: 100%;
        height: 210px;
        // border: 1px solid #fff;
      }
      .right-bottom {
        width: 100%;
        height: calc(100% - 460px);
        // border: 1px solid #fff;
      }
    }
  }
}
.bottom-charts {
  position: absolute;
  background: transparent;
  bottom: 30px;
  display: flex;
  .title-wrapper {
    text-align: center;
  }
  .el-card {
    background: transparent;
    &:nth-child(2) {
      margin-left: 20px;
    }
    span {
      padding: 0 6px;
    }
  }
}
.patient-wrapper {
  position: absolute;
  right: 370px;
  top: 252px;
  // bottom: 0px;
  width: 210px;
  .patient-chart-wrapper {
    width: inherit;
    height: 100%;
  }
}
.modal-style {
  position: absolute;
  width: 300px;
  // height: 280px;
  background: #fff;
  transform-origin: center top;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  word-break: break-all;
  border-radius: 8px;
  z-index: 999;
  opacity: 0.85;
  .header {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
    font-size: 15px;
    .title {
      font-weight: 700;
      padding: 12px 0 12px 12px;
    }
    .close {
      padding: 12px 15px 12px 0;
      cursor: pointer;
    }
  }
  .body {
    padding: 10px 15px 20px 15px;
    font-size: 14px;
    min-height: 100px;
  }
}
</style>
